package com.carbon.assets.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.carbon.assets.entity.CarbonAssets;
import com.carbon.assets.entity.CarbonMetaregistry;
import com.carbon.assets.mapper.CarbonAssetsMapper;
import com.carbon.assets.param.CarbonAssetsQueryParam;
import com.carbon.assets.param.CarbonCreditAssetsAddParam;
import com.carbon.assets.service.CarbonAssetsService;
import com.carbon.assets.service.CarbonCreditAssetsService;
import com.carbon.assets.param.CarbonCreditAssetsQueryParam;
import com.carbon.assets.service.CarbonMetaregistryService;
import com.carbon.assets.service.DictService;
import com.carbon.assets.vo.CarbonAssetsTotalVo;
import com.carbon.assets.vo.CarbonCreditAssetsQueryVo;
import com.carbon.assets.entity.CarbonCreditAssets;
import com.carbon.assets.common.BaseController;
import com.carbon.assets.vo.DictVo;
import com.carbon.assets.vo.SelectorVo;
import com.carbon.domain.common.ApiResult;
import com.carbon.common.api.Paging;
import com.carbon.trade.entity.CarbonTradeQuote;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>
 * 碳信用资产 前端控制器
 * </p>
 *
 * @author Li Jun
 * @since 2022-04-24
 */
@Slf4j
@RestController
@RequestMapping("/carbonCreditAssets")
@Api(value = "碳信用资产模块", tags = {"碳信用资产模块"})
public class CarbonCreditAssetsController extends BaseController {
   @Resource
    CarbonCreditAssetsService carbonCreditAssetsService;
   @Resource
    DictService dictService;
   @Resource
    CarbonMetaregistryService carbonMetaregistryService;

    /**
     * 查找碳信用的持仓量等数据的总和
     */
    @GetMapping("/queryCreditAssetsSum")
    public ApiResult queryCreditAssetsSum(@RequestParam String tenantId){
         LambdaQueryWrapper<CarbonCreditAssets> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CarbonCreditAssets::getTenantId, tenantId);
        List<CarbonCreditAssets> list = carbonCreditAssetsService.list(queryWrapper);
        CarbonCreditAssetsQueryVo carbonCreditAssetsQueryVo = new CarbonCreditAssetsQueryVo();
        BigDecimal totalSum = BigDecimal.ZERO;
        BigDecimal availableAmountSum = BigDecimal.ZERO;
        BigDecimal frozenAmountSum = BigDecimal.ZERO;
        BigDecimal lockedAmountSum = BigDecimal.ZERO;
        for (CarbonCreditAssets carbonCreditAssets : list) {
            totalSum = totalSum.add(carbonCreditAssets.getTotal() != null ? carbonCreditAssets.getTotal() : BigDecimal.ZERO);
            availableAmountSum = availableAmountSum.add(carbonCreditAssets.getAvailableAmount() != null ? carbonCreditAssets.getAvailableAmount() : BigDecimal.ZERO);
            frozenAmountSum = frozenAmountSum.add(carbonCreditAssets.getFrozenAmount() != null ? carbonCreditAssets.getFrozenAmount() : BigDecimal.ZERO);
            lockedAmountSum = lockedAmountSum.add(carbonCreditAssets.getLockedAmount() != null ? carbonCreditAssets.getLockedAmount() : BigDecimal.ZERO);
        }
// 赋值给查询VO对象
        carbonCreditAssetsQueryVo.setTotal(totalSum);
        carbonCreditAssetsQueryVo.setAvailableAmount(availableAmountSum);
        carbonCreditAssetsQueryVo.setFrozenAmount(frozenAmountSum);
        carbonCreditAssetsQueryVo.setLockedAmount(lockedAmountSum);
        return ApiResult.ok(carbonCreditAssetsQueryVo);
    }
    /**
     * 查找碳信用每一条数据前端展示
     */

    /**
     * 上传项目信息
     * @param carbonCreditAssets
     * @return
     */
    @PostMapping("/upload")
    public ApiResult upload(@RequestBody CarbonCreditAssets carbonCreditAssets,@RequestParam("rid") String rid) {
        CarbonMetaregistry cm = carbonMetaregistryService.getById(rid);
        String remainingReductionStr = cm.getRemainingReduction(); // String类型
        BigDecimal total = carbonCreditAssets.getTotal(); // BigDecimal类型
        BigDecimal remainingReductionBigDec = null;
        try {
            remainingReductionBigDec = new BigDecimal(remainingReductionStr.trim());
            BigDecimal resultBigDec = remainingReductionBigDec.subtract(total);
            String resultStr = resultBigDec.stripTrailingZeros().toPlainString();
            if (Integer.parseInt(resultStr)<0){
                return ApiResult.fail("可用持仓量不足");
            }
            cm.setRemainingReduction(resultStr);
            carbonMetaregistryService.updateById(cm);
        } catch (NumberFormatException e) {
            throw new RuntimeException("剩余减排量格式错误，无法计算：" + remainingReductionStr, e);
        }
        carbonCreditAssets.setCarbonProjectRefId(cm.getRefId());
        carbonCreditAssets.setCarbonProjectId((long)cm.getId());
        carbonCreditAssets.setAvailableAmount(carbonCreditAssets.getTotal());
        carbonCreditAssets.setAssetsStatus("0130000001");
        carbonCreditAssets.setTransactionStatus("0160000001");
        carbonCreditAssets.setValuation(carbonCreditAssets.getTotal().multiply(BigDecimal.valueOf(50)));
        boolean b = carbonCreditAssetsService.save(carbonCreditAssets);
        return ApiResult.ok();
    }

    @PutMapping("/update")
    public ApiResult update(@RequestBody CarbonCreditAssets carbonCreditAssets,@RequestParam("modifyPrice") String modifyPrice) {
        Long id = carbonCreditAssets.getCarbonProjectId();
        BigDecimal lockedAmount = carbonCreditAssetsService.getById(carbonCreditAssets.getId()).getLockedAmount();
        CarbonMetaregistry cm = carbonMetaregistryService.getById(id);
        //cm里的余额
        String remainingReductionStr = cm.getRemainingReduction();
        //修改之前写的持仓总量
        BigDecimal modifyPriceDec = new BigDecimal(modifyPrice.trim());
        BigDecimal remainingReductionBigDec = null;
        BigDecimal total2 = carbonCreditAssets.getTotal();
        try {
            remainingReductionBigDec = new BigDecimal(remainingReductionStr.trim());
            //加上修改前的持仓总量，回到原本状态
            BigDecimal resultBigDec = remainingReductionBigDec.add(modifyPriceDec);
            //再减去新填进来的要修改的持仓量
            resultBigDec = resultBigDec.subtract(total2);
            if(resultBigDec.compareTo(BigDecimal.ZERO) < 0){
                    return ApiResult.fail("持仓量不足");
            }
            String resultStr = resultBigDec.stripTrailingZeros().toPlainString();
            cm.setRemainingReduction(resultStr);
            //修改到cm里面
            carbonMetaregistryService.updateById(cm);
        } catch (NumberFormatException e) {
            throw new RuntimeException("剩余减排量格式错误，无法计算：" + remainingReductionStr, e);
        }
        carbonCreditAssets.setAvailableAmount(carbonCreditAssets.getTotal().subtract(lockedAmount));
        carbonCreditAssets.setValuation(carbonCreditAssets.getTotal().multiply(BigDecimal.valueOf(50)));
        carbonCreditAssetsService.updateById(carbonCreditAssets);
        return ApiResult.ok("修改成功");
    }

    /**
     * 查询项目列表
     * @param page
     * @param pageSize
     * @param projectName
     * @param tenantId
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("获取碳信用资产项目列表")
    public ApiResult<Map<String, Object>> getProjectList(
            @ApiParam(value = "当前页码", required = true) @RequestParam Integer page,
            @ApiParam(value = "每页条数", required = true) @RequestParam Integer pageSize,
            @ApiParam(value = "项目名称（模糊查询）") @RequestParam(required = false) String projectName,
            @ApiParam(value = "租户ID", required = true) @RequestParam Long tenantId) {

        // 创建分页对象
        Page<CarbonMetaregistry> pagination = new Page<>(page, pageSize);

        IPage<CarbonMetaregistry> resultPage = carbonCreditAssetsService.queryProjectList(
                pagination, projectName, tenantId);

        // 过滤掉remainingReduction为0的记录（String类型处理）
        List<CarbonMetaregistry> filteredRecords = resultPage.getRecords().stream()
                .filter(item -> {
                    // 获取剩余量字符串
                    String remainingReduction = item.getRemainingReduction();
                    // 处理null或空字符串的情况（视为不符合条件）
                    if (remainingReduction == null || remainingReduction.trim().isEmpty()) {
                        return false;
                    }
                    String trimmedValue = remainingReduction.trim();
                    return !"0".equals(trimmedValue) && !"0.0".equals(trimmedValue);
                })
                .collect(Collectors.toList());
        // 重新计算分页参数（基于过滤后的数据）
        int filteredTotal = filteredRecords.size();
        int filteredPages = (int) Math.ceil((double) filteredTotal / pageSize);

        Map<String, Object> data = new HashMap<>();
        data.put("records", filteredRecords);         // 过滤后的数据列表
        data.put("total", filteredTotal);             // 过滤后的总记录数
        data.put("pages", filteredPages);             // 过滤后的总页数
        data.put("current", page);                    // 当前页码保持不变
        data.put("size", pageSize);                   // 每页条数保持不变

        return ApiResult.ok(data);
    }
    /**
     * 查询项目可用余额
     * @param projectId
     * @return
     */
    @GetMapping("/queryTotal/{projectId}")
    ApiResult<BigDecimal> queryTotal(@PathVariable("projectId") Long projectId){
        return ApiResult.ok(carbonCreditAssetsService.getByCarbonProjectId(projectId).getAvailableAmount());
    }


    /**
     * 更新项目可用余额以及冻结余额
     * @param carbonTradeQuote
     * @return
     */
    @PostMapping("/updateAmount")
    ApiResult updateAmount(@RequestBody CarbonTradeQuote carbonTradeQuote){
        carbonCreditAssetsService.updateAmount(carbonTradeQuote.getProjectId(),carbonTradeQuote.getTradeQuantity());
        return ApiResult.ok();
    }

    /**
     * 详情页面展示特定一条数据
     */
    @GetMapping("/queryCreditAssets")
    public ApiResult queryCreditAssets(@RequestParam String tenantId,String id) {
        // 查询所有符合条件的数据列表
        CarbonCreditAssetsQueryVo carbonCreditAssetsQueryVo = carbonCreditAssetsService.queryJoinOneCreditAssets(id, tenantId);
         return ApiResult.ok(carbonCreditAssetsQueryVo);
    }
    /**
     * 删除一条数据
     */
    @DeleteMapping("/delCreditAssets")
    public ApiResult delCreditAssets(@RequestParam String id) {
        CarbonCreditAssets cca = carbonCreditAssetsService.getById(id);
        String refId = cca.getCarbonProjectRefId();
        BigDecimal total = cca.getTotal();
        QueryWrapper<CarbonMetaregistry> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ref_id", refId); // 假设数据库字段名为ref_id
        CarbonMetaregistry cm = carbonMetaregistryService.getOne(queryWrapper);
        String remainingReductionStr = cm.getRemainingReduction();
        BigDecimal remainingReduction = new BigDecimal(remainingReductionStr);
        BigDecimal newRemaining = remainingReduction.add(total); // 核心：相加操作
        // 转换为String并优化格式
        cm.setRemainingReduction(newRemaining.stripTrailingZeros().toPlainString());
        carbonMetaregistryService.updateById(cm);
        boolean isDeleted = carbonCreditAssetsService.removeById(id);

        if (isDeleted) {
            return ApiResult.ok("成功删除");
        }else {
            return  ApiResult.fail("没有该条数据");
        }
    }
    /**
     * 查询字典，渲染到下拉栏上
     */
    @GetMapping("/querySelector")
    public ApiResult querySelector() {
        Map<String, List<DictVo>> dataMap = new HashMap<>();
        String dictCode = "007";
        LambdaQueryWrapper<DictVo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DictVo::getDictCode, dictCode);
        List<DictVo> list = dictService.list(queryWrapper);
        dataMap.put("certificationList", list);

        String dictCode2 = "016";
        LambdaQueryWrapper<DictVo> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(DictVo::getDictCode, dictCode2);
        List<DictVo> list2 = dictService.list(queryWrapper2);
        dataMap.put("transactionStatusList", list2);
        //资产状态
        String dictCode3 = "013";
        LambdaQueryWrapper<DictVo> queryWrapper3 = new LambdaQueryWrapper<>();
        queryWrapper3.eq(DictVo::getDictCode, dictCode3);
        List<DictVo> list3 = dictService.list(queryWrapper3);
        dataMap.put("assetsStatusList", list3);

        //交割方式
        String dictCode4 = "019";
        LambdaQueryWrapper<DictVo> queryWrapper4 = new LambdaQueryWrapper<>();
        queryWrapper4.eq(DictVo::getDictCode, dictCode4);
        List<DictVo> list4 = dictService.list(queryWrapper4);
        dataMap.put("deliveryMethodList", list4);

        //交割场所
        String dictCode5 = "017";
        LambdaQueryWrapper<DictVo> queryWrapper5 = new LambdaQueryWrapper<>();
        queryWrapper5.eq(DictVo::getDictCode, dictCode5);
        List<DictVo> list5 = dictService.list(queryWrapper5);
        dataMap.put("deliveryExchangeList", list5);


        //领域
        String dictCode6 = "003";
        LambdaQueryWrapper<DictVo> queryWrapper6 = new LambdaQueryWrapper<>();
        queryWrapper6.eq(DictVo::getDictCode, dictCode6);
        List<DictVo> list6 = dictService.list(queryWrapper6);
        dataMap.put("projectScopeList", list6);

        //资产类型
        String dictCode7 = "014";
        LambdaQueryWrapper<DictVo> queryWrapper7 = new LambdaQueryWrapper<>();
        queryWrapper7.eq(DictVo::getDictCode, dictCode7);
        List<DictVo> list7 = dictService.list(queryWrapper7);
        dataMap.put("assetTypeList", list7);

        //项目类型
        String dictCode8 = "004";
        LambdaQueryWrapper<DictVo> queryWrapper8 = new LambdaQueryWrapper<>();
        queryWrapper8.eq(DictVo::getDictCode, dictCode8);
        List<DictVo> list8 = dictService.list(queryWrapper8);
        dataMap.put("projectTypeList", list8);

        //签发机构
        String dictCode9 = "044";
        LambdaQueryWrapper<DictVo> queryWrapper9 = new LambdaQueryWrapper<>();
        queryWrapper9.eq(DictVo::getDictCode, dictCode9);
        List<DictVo> list9 = dictService.list(queryWrapper9);
        dataMap.put("issuingAgencyList", list9);

        //行业
        String dictCode10 = "002";
        LambdaQueryWrapper<DictVo> queryWrapper10 = new LambdaQueryWrapper<>();
        queryWrapper10.eq(DictVo::getDictCode, dictCode10);
        List<DictVo> list10 = dictService.list(queryWrapper10);
        dataMap.put("industoryList", list10);

        //方法学
        String dictCode11 = "009";
        List<DictVo> list11 = dictService.getMethodCode(dictCode11);
        dataMap.put("methodologyList", list11);

        //国家
        String dictCode12 = "006";
        LambdaQueryWrapper<DictVo> queryWrapper12 = new LambdaQueryWrapper<>();
        queryWrapper12.eq(DictVo::getDictCode, dictCode12);
        List<DictVo> list12 = dictService.list(queryWrapper12);
        dataMap.put("countryList", list12);

        //省
        String dictCode13 = "011";
        LambdaQueryWrapper<DictVo> queryWrapper13 = new LambdaQueryWrapper<>();
        queryWrapper13.eq(DictVo::getDictCode, dictCode13);
        List<DictVo> list13 = dictService.list(queryWrapper13);
        dataMap.put("provinceList", list13);
        //项目状态
        String dictCode14 = "010";
        LambdaQueryWrapper<DictVo> queryWrapper14 = new LambdaQueryWrapper<>();
        queryWrapper14.eq(DictVo::getDictCode, dictCode14);
        List<DictVo> list14 = dictService.list(queryWrapper14);
        dataMap.put("projectStatusList", list14);

        //文件类型
        String dictCode15 = "021";
        LambdaQueryWrapper<DictVo> queryWrapper15 = new LambdaQueryWrapper<>();
        queryWrapper15.eq(DictVo::getDictCode, dictCode15);
        List<DictVo> list15 = dictService.list(queryWrapper15);
        list15.remove(0);
        dataMap.put("fileTypeList", list15);

        //核证机构
        String dictCode16 = "052";
        LambdaQueryWrapper<DictVo> queryWrapper16 = new LambdaQueryWrapper<>();
        queryWrapper16.eq(DictVo::getDictCode, dictCode16);
        List<DictVo> list16 = dictService.list(queryWrapper16);
        list16.remove(0);
        dataMap.put("issuingAgencyList", list16);

        //方法学状态
        String dictCode17 = "045";
        LambdaQueryWrapper<DictVo> queryWrapper17 = new LambdaQueryWrapper<>();
        queryWrapper17.eq(DictVo::getDictCode, dictCode17);
        List<DictVo> list17 = dictService.list(queryWrapper17);
        list17.remove(0);
        dataMap.put("statusCodeList", list17);


        return ApiResult.ok(dataMap);

    }

    @GetMapping("/queryBySelector")
    public ApiResult queryBySelector(SelectorVo selectorVo) {
        // 1. 验证必填参数
        if (selectorVo.getTenantId() == null || selectorVo.getTenantId().isEmpty()) {
            return ApiResult.fail("租户ID不能为空");
        }
        // 2. 创建分页对象（使用Vo中的分页参数）
        Page<CarbonCreditAssetsQueryVo> page = new Page<>(
                selectorVo.getPageNum(),
                selectorVo.getPageSize()
        );
        // 3. 调用服务层的分页查询方法
        Page<CarbonCreditAssetsQueryVo> resultPage =
                carbonCreditAssetsService.selectBySelector(page, selectorVo);

        // 4. 构建包含分页信息的返回结果
        return ApiResult.ok(resultPage);
    }
}

